package com.sanshengshui.netty.nio;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Demo {

    static String  basePath ="E:\\ideaworkspace\\netty-learning-example\\netty-helloworld\\src\\main\\resource\\";

    /**
     * 客户端建立 tcp 链接
     * @throws IOException
     */
    @Test
    public  void client() throws IOException {
        FileChannel fileChannel = FileChannel.open(Paths.get(basePath+"logMonitor.txt"));
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1",8080));
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (fileChannel.read(byteBuffer)!=-1){
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        fileChannel.close();
        socketChannel.close();
    }
    /**
     * 服务接收字节
     * @throws IOException
     */
    @Test
    public  void serve() throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        SocketChannel socketChannel =serverSocketChannel.accept();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        FileChannel fileChannel = FileChannel.open(Paths.get(basePath+"logMonitor1.txt"), StandardOpenOption.CREATE,StandardOpenOption.WRITE);
        while (socketChannel.read(byteBuffer)!=-1){
            byteBuffer.flip();
            fileChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        fileChannel.close();
        socketChannel.close();
    }

}
